/**
 * 文件上传相关 API
 */

import axios from 'axios'
import { ElMessage } from 'element-plus'

const baseURL = import.meta.env.VITE_API_BASE || 'http://127.0.0.1:7002'

/**
 * 上传单个文件到七牛云
 * @param {File} file - 文件对象
 * @param {Function} onProgress - 上传进度回调
 * @returns {Promise<Object>} 上传结果
 */
export const uploadFile = async (file, onProgress) => {
  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await axios.post(`${baseURL}/api/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(percentCompleted)
        }
      },
    })

    if (response.data.code === 0) {
      return {
        success: true,
        data: response.data.data,
      }
    } else {
      throw new Error(response.data.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传文件失败:', error)
    throw error
  }
}

/**
 * 批量上传文件到七牛云
 * @param {Array<File>} files - 文件数组
 * @param {Function} onProgress - 上传进度回调
 * @returns {Promise<Object>} 上传结果
 */
export const uploadFiles = async (files, onProgress) => {
  const formData = new FormData()
  files.forEach((file) => {
    formData.append('files', file)
  })

  try {
    const response = await axios.post(`${baseURL}/api/upload/batch`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (onProgress) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(percentCompleted)
        }
      },
    })

    if (response.data.code === 0) {
      return {
        success: true,
        data: response.data.data,
      }
    } else {
      throw new Error(response.data.msg || '上传失败')
    }
  } catch (error) {
    console.error('批量上传失败:', error)
    throw error
  }
}

/**
 * 获取七牛云上传 Token
 * @returns {Promise<Object>} Token 信息
 */
export const getUploadToken = async () => {
  try {
    const response = await axios.get(`${baseURL}/api/upload/token`)

    if (response.data.code === 0) {
      return {
        success: true,
        data: response.data.data,
      }
    } else {
      throw new Error(response.data.msg || '获取Token失败')
    }
  } catch (error) {
    console.error('获取Token失败:', error)
    throw error
  }
}

/**
 * 上传图片的辅助函数（带进度提示）
 * @param {File} file - 图片文件
 * @returns {Promise<Object>} 上传结果 { success: true, data: { url: '...' } }
 */
export const uploadImage = async (file) => {
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return { success: false, message: '只能上传图片文件' }
  }

  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return { success: false, message: '图片大小不能超过5MB' }
  }

  try {
    const result = await uploadFile(file, (percent) => {
      console.log(`上传进度: ${percent}%`)
    })

    if (result.success) {
      return {
        success: true,
        data: {
          url: result.data.url
        }
      }
    } else {
      return { success: false, message: '上传失败' }
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    return {
      success: false,
      message: error.message || '上传图片失败'
    }
  }
}

/**
 * 批量上传图片的辅助函数
 * @param {Array<File>} files - 图片文件数组
 * @returns {Promise<Array<string>>} 图片 URL 数组
 */
export const uploadImages = async (files) => {
  // 验证所有文件
  for (const file of files) {
    if (!file.type.startsWith('image/')) {
      ElMessage.error('只能上传图片文件')
      throw new Error('只能上传图片文件')
    }
    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error(`图片 ${file.name} 大小不能超过5MB`)
      throw new Error('图片大小超限')
    }
  }

  try {
    // 逐个上传（更好的进度控制）
    const urls = []
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      ElMessage.info(`正在上传第 ${i + 1}/${files.length} 张图片...`)

      const result = await uploadFile(file)
      if (result.success) {
        urls.push(result.data.url)
      }
    }

    ElMessage.success(`成功上传 ${urls.length} 张图片`)
    return urls
  } catch (error) {
    ElMessage.error('批量上传图片失败: ' + error.message)
    throw error
  }
}

